<template>
    <view class="order-container">
        <!-- 线路标题 -->
        <view class="line-title">{{ route.title }}</view>

        <scroll-view scroll-y class="form-container">
            <!-- 出发地 -->
            <view class="form-item">
                <text class="label">出发地</text>
                <text class="readonly-text">{{ route.start_address }}</text>
            </view>

            <!-- 目的地 -->
            <view class="form-item">
                <text class="label">目的地</text>
                <text class="readonly-text">{{ route.end_address }}</text>
            </view>

            <!-- 出行日期与时间 -->
            <view class="form-item date-container">
                <text class="label">出行时间</text>
                <view class="time-selection">
                    <text>{{ selectedDate }}</text>

                    <picker
                        mode="selector"
                        range-key="time"
                        :range="timeSlots"
                        @change="selectTimeSlot"
                    >
                        <text class="time-slot-text">{{ selectedTimeSlot || '请选择时段' }}</text>
                        <u-icon name="arrow-right" size="30" class="arrow-icon" />
                    </picker>
                </view>
            </view>

            <!-- 乘车地点 -->
            <view class="form-item">
                <view class="input-group">
                    <text class="label">乘车地点</text>
                    <view class="input-container">
                        <input
                            v-model="formData.start_address"
                            placeholder="请输入乘车地点"
                            class="input-field"
                            name="start_address"
                        />
                        <u-icon name="map" size="40" class="map-icon" @click="openMapLocation" />
                    </view>
                </view>
            </view>

            <!-- 出行人信息 -->
            <view class="travelers-section">
                <text class="section-title">出行须填写</text>
                <text class="section_toast">需按出行所持证件信息填写</text>

                <view class="add-traveler-button">
                    新增/选择
                    <u-icon name="arrow-right" @click="addTraveler" />
                </view>
                <view v-for="(traveler, index) in travelers" :key="index" class="traveler-card">
                    <u-icon
                        color="#f6a22d"
                        name="minus-circle"
                        size="36"
                        class="delete-icon"
                        @click="deleteTraveler(index)"
                    />
                    <view class="traveler-info">
                        <text class="traveler-name">{{ traveler.name }}</text>
                        <text class="traveler-phone"> {{ traveler.phone }}</text>
                    </view>
                    <u-icon
                        name="edit-pen"
                        size="36"
                        class="edit-icon"
                        @click="editTraveler(index)"
                    />
                </view>
            </view>
            <view class="payment-info">
                <text>总金额: ¥{{ totalPrice }}</text>
            </view>
        </scroll-view>

        <!-- 支付信息 -->

        <!-- 支付按钮 -->
        <view class="payment-footer">
            <button @click="submitOrder" class="commit_btn">支付</button>
        </view>
    </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { getLineDetail } from '@/api/lines'
import { apiOrderAdd } from '@/api/order'

const route = ref<any>({})
const routeId = ref(0)
const selectedDate = ref('')
const price = ref(0)
const adultCount = ref(0)
const childCount = ref(0)
const priceId = ref(0)

onLoad((options) => {
    routeId.value = options.lineId
    selectedDate.value = options.date
    price.value = Number(options.price)
    adultCount.value = Number(options.adultCount)
    childCount.value = Number(options.childCount)
    priceId.value = Number(options.priceId)
    getData(routeId.value)
})

const formData = ref({
    order_type: 1,
    people_num: 0,
    baggage_num: 0,
    estimated_time: '',
    price_id: priceId.value,
    line_id: routeId.value,
    start_address: '',
    end_address: '',
    travelers: [],
    price: 0
})

watch(priceId, (newVal) => {
    formData.value.price_id = newVal
})

const getData = async (id) => {
    route.value = await getLineDetail({ id })
}

// 时间段选项
const timeSlots = ref([
    { time: '00:00-02:00' },
    { time: '02:00-04:00' },
    { time: '04:00-06:00' },
    { time: '06:00-08:00' },
    { time: '08:00-10:00' },
    { time: '10:00-12:00' },
    { time: '14:00-16:00' },
    { time: '16:00-18:00' },
    { time: '18:00-20:00' },
    { time: '20:00-22:00' },
    { time: '22:00-24:00' }
])
const selectedTimeSlot = ref('')
// 出行人列表
const travelers = ref([
    { name: '张三', phone: '13800000000', luggageCount: 2 },
    { name: '李四', phone: '13900000000', luggageCount: 1 }
])
// 表单数据

// 总价计算
const totalPrice = computed(() => {
    return price.value * travelers.value.length
})

// 选择时间段
function selectTimeSlot(e: any) {
    selectedTimeSlot.value = timeSlots.value[e.detail.value].time
    formData.value.estimated_time = selectedDate.value + ' ' + selectedTimeSlot.value
}

// 新增出行人
function addTraveler() {
    uni.navigateTo({
        url: '/pages/traveler_list/traveler_list'
    })
}

function editTraveler(index: number) {
    uni.navigateTo({
        url: `/pages/traveler_edit/traveler_edit?mode=edit&index=${index}`
    })
}

function deleteTraveler(index: number) {
    travelers.value.splice(index, 1)
}

function openMapLocation() {
    uni.chooseLocation({
        success: (res) => {
            formData.value.start_address = res.address + res.name
        },
        fail: () => {
            uni.showToast({ title: '定位失败', icon: 'none' })
        }
    })
}

const totalLuggage = computed(() => {
    return travelers.value.reduce((sum, traveler) => sum + (traveler.luggageCount || 0), 0)
})

// 提交订单
const submitOrder = async () => {
    formData.value.line_id = routeId.value
    formData.value.end_address = route.value.end_address
    formData.value.people_num = travelers.value.length
    formData.value.baggage_num = totalLuggage.value
    formData.value.travelers = JSON.stringify(travelers.value)
    formData.value.price = price.value * travelers.value.length
    if (
        !formData.value.price_id ||
        !formData.value.start_address ||
        travelers.value.length === 0 ||
        !formData.value.end_address ||
        !formData.value.line_id ||
        !formData.value.people_num ||
        !formData.value.baggage_num ||
        !formData.value.travelers
    ) {
        uni.showToast({ title: '请完善信息', icon: 'none' })
        return
    }

    //验证支付条件
    uni.showModal({
        title: '确认支付',
        content: `您将支付 ¥${formData.value.price}`,
        success: async (res) => {
            if (res.confirm) {
                // 调用支付接口
                // uni.requestPayment({
                //     // 支付参数
                // })
                await apiOrderAdd(formData.value)
            }
        }
    })
}

onMounted(() => {
    const travelerSavedHandler = (travelerData) => {
        travelers.value.push({
            id: Date.now(), // 生成唯一 ID
            name: travelerData.name,
            phone: travelerData.phone,
            luggageCount: travelerData.luggageCount
        })
    }
    uni.$on('travelerSaved', travelerSavedHandler)

    // 返回时清理事件监听
    onUnmounted(() => {
        uni.$off('travelerSaved', travelerSavedHandler)
    })
})
</script>

<style lang="scss" scoped>
.order-container {
    padding: 20rpx;
    background-color: #f5f5f5;
}

.line-title {
    font-size: 36rpx;
    font-weight: bold;
    margin-bottom: 30rpx;
}

.form-container {
    height: calc(100vh - 200rpx);
}

.form-item {
    margin-bottom: 25rpx;
    background-color: #fff;
    padding: 20rpx;
    border-radius: 16rpx;

    .input-group {
        display: flex;
        align-items: center; // 水平居中所有元素
        gap: 20rpx; // 标签与输入区域之间的间距
    }

    // 输入框 + 图标 容器
    .input-container {
        display: flex;
        align-items: center; // 输入框与图标水平对齐
        flex: 1; // 占据剩余空间
    }

    .input-field {
        flex: 1;
        padding: 20rpx;
        border: none;
        border-radius: 8rpx;
        font-size: 28rpx;
    }

    .input-field.error {
        border-color: #ff4949;
    }

    /* 仅 placeholder 靠右 */
    .input-field::-webkit-input-placeholder {
        text-align: right;
    }

    // 地图图标样式
    .map-icon {
        margin-left: 10rpx; // 图标与输入框间距
        padding: 10rpx;
        border-left: 1rpx solid #eee; // 图标左侧分隔线
    }
}

.label {
    font-size: 28rpx;
    color: #666;
}

input {
    border: 1rpx solid #eee;
    padding: 20rpx;
    border-radius: 8rpx;
}

.readonly-text {
    color: #333;
    padding: 20rpx;
}

.time-selection {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.date-text,
.time-slot-text {
    padding: 20rpx;
    color: #333;
}

.travelers-section {
    margin-top: 30rpx;
    background-color: #fff;
    padding: 20rpx;
    border-radius: 16rpx;
}

.section-title {
    display: block;
    margin-bottom: 15rpx;
    font-size: 40rpx;
}

.section_toast {
    color: #666666;
}

.traveler-card {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15rpx 0;
    border-bottom: 1rpx solid #eee;
}

.traveler-info {
    margin-left: 20rpx;
    display: flex;
    flex: 1;
    flex-direction: column;
    margin-bottom: 20rpx;
}

.traveler-name {
    font-size: 36rpx;
    font-weight: bold;
}

.traveler-phone {
    font-size: 28rpx;
    color: #666;
}

.payment-info {
    margin-top: 20rpx;
    padding: 20rpx;
    background-color: #fff;
    text-align: right;
    font-size: 32rpx;
    font-weight: bold;
    border-radius: 16rpx;
}

.payment-footer {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 20rpx;
    background-color: #fff;
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.add-traveler-button {
    display: flex;
    margin-top: 40rpx;
    background-color: #fffbf6;
    border: 1rpx solid #fbdaab;
    color: #f6a22d;
    padding: 20rpx;
    border-radius: 8rpx;
    font-size: 32rpx;
    justify-content: space-between;
    align-items: center;
}

.date-container {
    display: flex;
    justify-content: space-between;
}
</style>
